"""
数学研究模块
包含各种数学建模和分析工具
"""

import numpy as np
from scipy.integrate import odeint
from scipy.optimize import differential_evolution

class MathematicalResearch:
    """数学建模与分析工具集"""

    @staticmethod
    def linear_regression(x, y):
        """线性回归分析
        参数:
            x: 自变量数组
            y: 因变量数组
        返回:
            斜率, 截距
        """
        n = len(x)
        sum_x = sum(x)
        sum_y = sum(y)
        sum_xy = sum(xi*yi for xi, yi in zip(x, y))
        sum_x2 = sum(xi**2 for xi in x)
        
        slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x**2)
        intercept = (sum_y - slope * sum_x) / n
        
        return slope, intercept

    @staticmethod
    def polynomial_regression(x, y, degree=2):
        """多项式回归分析
        参数:
            x: 自变量数组
            y: 因变量数组
            degree: 多项式次数(默认2)
        返回:
            多项式系数数组(从高次到低次)
        """
        coeffs = np.polyfit(x, y, degree)
        return coeffs.tolist()

    @staticmethod
    def time_series_analysis(data, window_size=3):
        """时间序列分析(移动平均)
        参数:
            data: 时间序列数据
            window_size: 移动窗口大小(默认3)
        返回:
            平滑后的时间序列
        """
        smoothed = []
        for i in range(len(data)):
            start = max(0, i - window_size + 1)
            end = i + 1
            smoothed.append(sum(data[start:end]) / (end - start))
        return smoothed

    @staticmethod
    def standardize_data(data):
        """数据标准化处理(Z-score标准化)
        参数:
            data: 原始数据数组
        返回:
            标准化后的数据
        """
        mean = np.mean(data)
        std_dev = np.std(data)
        return [(x - mean) / std_dev for x in data]

    @staticmethod
    def differential_equation_solver(func, initial_condition, t_range):
        """常微分方程数值解
        参数:
            func: 微分方程函数
            initial_condition: 初始条件
            t_range: 时间范围
        返回:
            数值解
        """
        solution = odeint(func, initial_condition, t_range)
        return solution